package com.gack.business.service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.OSSClient;
import com.gack.business.dao.UserDao;
import com.gack.business.model.User;
import com.gack.business.model.UserLoginRecord;
import com.gack.business.model.ValidateCodeCreateLog;
import com.gack.business.model.VideoIdentify;
import com.gack.business.model.VideoOpinion;
import com.gack.business.repository.UserLoginRecordRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.repository.ValidateCodeCreateLogRepository;
import com.gack.business.repository.VideoIdentifyRepository;
import com.gack.business.repository.VideoOpinionRepository;
import com.gack.helper.common.abstractobj.Result;
import com.gack.helper.common.util.MD5;
import com.gack.helper.common.util.OSSUnitHelper;
import com.gack.helper.common.util.SendCode;
import com.gack.helper.common.util.SystemHelper;
import com.gack.helper.common.util.ValidateCode;

/**
 * 
* @ClassName: UserHomeService 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author (ZhangXinYu)  
* @date 2018年6月12日 下午2:48:22 
* @version V1.0
 */
@Service
public class UserHomeService implements UserHomeServiceInterface{

	
	@Autowired
	private ValidateCodeCreateLogRepository validateCodeCreateLogRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private VideoOpinionRepository opinionRepository;
	@Autowired
	private UserLoginRecordRepository loginRecordRepository;
	@Autowired
	private VideoIdentifyRepository identifyRepository;
	@Autowired
	private UserDao userDao;
	
	/**
	 * 发送短信验证码
	 * result:: 1>>成功  -1>>失败
	 */
	@Override
	public Result sendIdentifyCode(String username){
		Result result = new Result();
//		User user = null;
//		List<User> users = userRepository.findByUsername(username);
//		if(users != null && users.size() > 0){
//			user = users.get(0);
//		}
//		if(userDao.getUserTodayOpinionCount(user == null ? username : user.getId())>0){
		if(userDao.getUserTodayOpinionCount(username,"pc")>0){
			result.setKey("error");
			result.setMsg("您今天的反馈次数已用完");
			return result;
		}
		List<VideoIdentify> identifys = identifyRepository.findByUsername(username);
		VideoIdentify identify = null;
		//用户名已存在  直接修改验证码   不存在  新添加验证信息
		if(identifys != null && identifys.size() > 0){
			identify = identifys.get(0);
		}else{
			identify = new VideoIdentify();
		}
		String code = SystemHelper.getSixCode();
		identify.setUsername(username);
		identify.setIdentifycode(code);
		identify.setIdentifytime(new Date());
//		String msg = "尊敬的用户您好，您的短信验证码为 "+code+"，有效时间为5分钟，请及时使用";
		String msg = "您好，您反馈问题的验证码是："+code+" ，有效时间5分钟。";
		try{
			SendCode.sendMessage(username, msg);
			result.setKey("success");
			result.setValue("验证码发送成功");
		}catch (Exception e) {
			e.printStackTrace();
			result.setKey("error");
			result.setKey("验证码发送失败，请再次尝试");
		}
		identifyRepository.save(identify);
		return result;
	}
	
	/**
	 * 获取图片验证码 
	 * 生成图片验证码  把验证码图片上传到oss中  返回url
	 */
	@Override
	public Map<String, Object> getIdentifyPic(){
		Map<String, Object> map = new HashMap<>();
		ValidateCodeCreateLog validateCodeCreateLog = null;
		ValidateCode validateCode = new ValidateCode();
		validateCode.createCode();
		BufferedImage buffImg = validateCode.getBuffImg();
		//bufferedImage 转  InputStream
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try{
			ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
			ImageIO.write(buffImg, "jpg", imageOutput);
		}catch (Exception e) {
			e.printStackTrace();
		}
	    InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
		//验证码图片上传到oss中
		if(buffImg!=null){
			OSSUnitHelper ossunit=new OSSUnitHelper();
			OSSClient client=OSSUnitHelper.getOSSClient();
			String diskName = "datas/video/identify/";
			String fileName = new Date().getTime() + (int) ((Math.random() * 9 + 1) * 100000) + ".png";
	        String md5key = OSSUnitHelper.uploadFile2OSS(client, inputStream, fileName,diskName);
	        String url="";
	        url=OSSUnitHelper.getUrl(client, diskName, fileName);
	        String urll=    url.substring(4, url.length());
	        url="https"+urll;
	        System.out.println(url+"5");
	        if(url!=null&&!url.equals("")){
	        	validateCodeCreateLog = new ValidateCodeCreateLog();
	        	validateCodeCreateLog.setCode(validateCode.getCode());
	        	validateCodeCreateLog.setPicUrl(url);
	        	validateCodeCreateLog.setPicName(fileName);
	        	validateCodeCreateLog.setCreateTime(new Date());
	        	validateCodeCreateLog = validateCodeCreateLogRepository.save(validateCodeCreateLog);
	        } 
		 }
		if(validateCodeCreateLog == null){
			map.put("key", "error");
			map.put("msg", "获取图片验证码失败");
			return map;
		}
		map.put("key", "success");
		map.put("url",validateCodeCreateLog.getPicUrl());
		map.put("code", validateCode.getCode());
		map.put("validateId", validateCodeCreateLog.getId());
		return map;
	}

	/**
	 * 首页登录
	 */
	@Override
	public Result homeLogin(String username, String password, String code, String validateid) {
		Result result = new Result();
//		if(code == null || code.equals("")){
//			result.setKey("error");
//			result.setMsg("验证码不可为空");
//			return result;
//		}
//		ValidateCodeCreateLog validateCodeCreateLog = validateCodeCreateLogRepository.findOne(validateid);
//		if(validateCodeCreateLog == null){
//			result.setKey("error");
//			result.setMsg("验证码不存在,登录失败");
//			return result;
//		}
//		if(!code.toUpperCase().equals(validateCodeCreateLog.getCode().toUpperCase())){
//			result.setKey("error");
//			result.setMsg("验证码错误，登录失败");
//			return result;
//		}
		List<User> users = userRepository.findByUsername(username);
		if(users == null || users.size() == 0){
			result.setKey("error");
			result.setMsg("您输入的手机号未注册");
			return result;
		}
		if(!users.get(0).isStatus()){
			result.setKey("error");
			result.setMsg("该账户已冻结,登录失败");
			return result;
		}
		password = MD5.md5(password);
		User user = userRepository.findUserByUsernameAndPassword(username, password);
		if(user == null ){
			result.setKey("error");
			result.setMsg("密码错误,登录失败");
			return result;
		}
		UserLoginRecord loginRecord = null;
		List<UserLoginRecord> loginRecords = loginRecordRepository.findByUsernameAndLoginResource(user.getId(),"web");
		if(loginRecords != null && loginRecords.size() > 0){
			loginRecord = loginRecords.get(0);
		}
		if(loginRecord == null){
			loginRecord = new UserLoginRecord();
			loginRecord.setUsername(user.getId());
			loginRecord.setLogin_resource("web");
		}
		loginRecord.setLogin_time(new Date());
		loginRecord.setEquipment("null");
		loginRecord = loginRecordRepository.save(loginRecord);
		//用户 登录次数+1
		userRepository.addOneLoginNum(user.getId());
		user.setLoginNum(user.getLoginNum() + 1);
		result.setKey("success");
		result.setValue(user);
		result.setMsg("登录成功");
		return result;
	}

	/**
	 * * @param @param opiniontext		意见内容
	* @param @param username		用户id  已登录为用户id  未登录为用户输入手机号
	* @param @param code			验证码
	* @param @param validateid		验证码记录id
	* @param @param type			类型 （0 未登录  1已登录）
	 */
	@Override
	public Result addHomeOpinion(String opiniontext, String username, String code, Integer type) {
		Result result = new Result();
		User user = null;
		if(type == 1 ){
			if(username == null || username.equals("")){
				result.setKey("error");
				result.setMsg("用户id不可为空");
				return result;
			}
			user = userRepository.findOne(username);
			if(user == null){
				result.setKey("error");
				result.setMsg("用户不存在,操作失败");
				return result;
			}
		}
		if(code == null || code.equals("")){
			result.setKey("error");
			result.setMsg("验证码不可为空");
			return result;
		}
		if(opiniontext == null || opiniontext.equals("")){
			result.setKey("error");
			result.setMsg("意见反馈不可为空");
			return result;
		}
		if(userDao.getUserTodayOpinionCount(user == null ? username : user.getId(),"pc")>0){
			result.setKey("error");
			result.setMsg("您今天的反馈次数已用完");
			return result;
		}
//		ValidateCodeCreateLog validateCodeCreateLog = validateCodeCreateLogRepository.findOne(validateid);
//		VideoIdentify identify = identifyRepository.
//		if(validateCodeCreateLog == null){
//			result.setKey("error");
//			result.setMsg("验证码查询不到,意见反馈提交失败");
//			return result;
//		}
//		if(!code.toUpperCase().equals(validateCodeCreateLog.getCode().toUpperCase())){
//			result.setKey("error");
//			result.setMsg("验证码错误，意见反馈提交失败");
//			return result;
//		}
		result = validateIdentify((0==type?username:user.getUsername()), code);
		if("error".equals(result.getKey())){
			return result;
		}
		VideoOpinion opinion = new VideoOpinion();
		opinion.setOpiniontext(opiniontext);
		// type 类型 （0 未登录  1已登录）
		if(type == 0){
			opinion.setUserid(username);
		}else{
			if(user != null){
				opinion.setUserid(user.getId());
			}else{
				opinion.setUserid(username);
			}
		}
		opinion.setCreateTime(new Date());
		opinion.setStatus(0);
		opinion.setSource("pc");
		opinion = opinionRepository.save(opinion);
		result.setKey("success");
		result.setValue(opinion);
		result.setMsg("意见反馈提交成功");
		return result;
	}
	
	/**
	 * 验证短信验证码
	 * result ：： 1>>验证成功  -2>>验证超时  -3>>验证码错误  -4>>失败，其他错误
	 */
	public Result validateIdentify(String username,String identifyCode){
		Result result = new Result();
		List<VideoIdentify> identifys = identifyRepository.findByUsername(username);
		if(identifys != null && identifys.size() > 0 && identifys.get(0).getIdentifytime() != null){
			VideoIdentify identify = identifys.get(0);
			Date nowDate = new Date();
			long alongTime = 0;	//时间差
			alongTime = nowDate.getTime() - identify.getIdentifytime().getTime();
			if(alongTime > 1000*60*5){
				//登录超时  登录失败
				result.setKey("error");
				result.setMsg("验证码超时，请重新获取验证码");
			}else if(!identifyCode.equals(identify.getIdentifycode())){
				//验证码错误
				result.setKey("error");
				result.setMsg("验证码错误，请确认验证码");
			}else{
				//验证通过
				result.setKey("success");
				result.setMsg("验证码验证通过");
			}
		}else{
			//该用户名不存在验证码信息   验证失败
			result.setKey("error");
			result.setMsg("验证失败，请先点击获取短信验证码");
		}
		return result;
	}

}
